package bean.managed;

import bean.managed.util.JsfUtil;
import bean.managed.util.PaginationHelper;
import bean.session.CalendarEntityFacade;

import entity.CalendarEntity;
import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.ResourceBundle;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import javax.faces.model.SelectItem;
import managedbean.AbstractBacking;
import org.primefaces.event.DateSelectEvent;
import type.DayOfWeek;

@ManagedBean(name = "calendarEntityController")
@SessionScoped
public class CalendarEntityController extends AbstractBacking implements Serializable {

    private CalendarEntity current;
    private DataModel items = null;
    @EJB
    private bean.session.CalendarEntityFacade ejbFacade;
    private PaginationHelper pagination;
    private Date publicHoliday;
    private String event;

    public CalendarEntityController() {
    }  
      
    public Date getPublicHoliday() {  
        return publicHoliday;  
    }  
  
    public void setPublicHoliday(Date publicHoliday) {  
        this.publicHoliday = publicHoliday;  
    }  
  
    public void handleDateSelect(DateSelectEvent event) {  
        publicHoliday = event.getDate();
        SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy"); 
        FacesContext facesContext = FacesContext.getCurrentInstance();  
        facesContext.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Public Holiday added", format.format(event.getDate()))); 
        setCurrent(new CalendarEntity());
        create();
    }  

    public CalendarEntity getSelected() {
        if (getCurrent() == null) {
            setCurrent(new CalendarEntity());
        }
        return getCurrent();
    }

    private CalendarEntityFacade getFacade() {
        return ejbFacade;
    }

    public PaginationHelper getPagination() {
        if (pagination == null) {
            pagination = new PaginationHelper(10) {

                @Override
                public int getItemsCount() {
                    return getFacade().count();
                }

                @Override
                public DataModel createPageDataModel() {
                    return new ListDataModel(getFacade().findRange(new int[]{getPageFirstItem(), getPageFirstItem() + getPageSize()}));
                }
            };
        }
        return pagination;
    }

    public String prepareList() {
        recreateModel();
        return "/entities/calendarEntity/List?faces-redirect=true";
    }

    public String prepareView() {
        setCurrent((CalendarEntity) getItems().getRowData());
        return "View";
    }

    public void prepareCreate() {
        setCurrent(new CalendarEntity());
        resetEvent();
    }

    public void create() {
        try {
            setCurrent(new CalendarEntity());
            getCurrent().setPublicHoliday(publicHoliday);
            getCurrent().setDay(publicHoliday.getDate());
            getCurrent().setMonth(publicHoliday.getMonth());
            getCurrent().setYear(publicHoliday.getYear()+1900);
            getCurrent().setDayOfWeek(publicHoliday.getDay());
            //if it is saturday/sunday, monday will be off-in-lieu
//            if (current.getDayOfWeek().equals(DayOfWeek.Saturday)) {
//                CalendarEntity saturday = new CalendarEntity();
//                Calendar monday = Calendar.getInstance();
//                monday.add(publicHoliday,2);
//            }
            getCurrent().setEvent(getEvent());
            getCurrent().created(getLoginPerson());
            getFacade().createPh(getCurrent());
            //JsfUtil.addSuccessMessage("Public Holiday added");
            recreateModel();
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
            e.printStackTrace();
        }
    }

    public String prepareEdit() {
        setCurrent((CalendarEntity) getItems().getRowData());
        return "Edit";
    }

    public String update() {
        try {
            current.modified(getLoginPerson());
            getFacade().edit(getCurrent());
            JsfUtil.addSuccessMessage("Public Holiday updated");
            return "View";
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
            return null;
        }
    }

    public String destroy() {
        setCurrent((CalendarEntity) getItems().getRowData());
        performDestroy();
        recreateModel();
        return "List";
    }

    public String destroyAndView() {
        performDestroy();
        recreateModel();
        return "List";
    }

    private void performDestroy() {
        try {
            current.modified(getLoginPerson());
            getFacade().remove(getCurrent());
            JsfUtil.addSuccessMessage("Public Holiday deleted");
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
        }
    }

    public DataModel getItems() {
        if (items == null) {
            items = getFacade().getAllSalesInquiry();
        }
        return items;
    }

    private void recreateModel() {
        items = null;
    }

    public SelectItem[] getItemsAvailableSelectMany() {
        return JsfUtil.getSelectItems(ejbFacade.findAll(), false);
    }

    public SelectItem[] getItemsAvailableSelectOne() {
        return JsfUtil.getSelectItems(ejbFacade.findAll(), true);
    }

    public String getEvent() {
        return event;
    }

    public void setEvent(String event) {
        this.event = event;
    }

    public CalendarEntity getCurrent() {
        return current;
    }

    public void setCurrent(CalendarEntity current) {
        this.current = current;
    }
    
    private void resetEvent() {
        setEvent("");
        current=null;
    }

    @FacesConverter(forClass = CalendarEntity.class)
    public static class CalendarEntityControllerConverter implements Converter {

        public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
            if (value == null || value.length() == 0) {
                return null;
            }
            CalendarEntityController controller = (CalendarEntityController) facesContext.getApplication().getELResolver().
                    getValue(facesContext.getELContext(), null, "calendarEntityController");
            return controller.ejbFacade.find(getKey(value));
        }

        java.lang.Long getKey(String value) {
            java.lang.Long key;
            key = Long.valueOf(value);
            return key;
        }

        String getStringKey(java.lang.Long value) {
            StringBuffer sb = new StringBuffer();
            sb.append(value);
            return sb.toString();
        }

        public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
            if (object == null) {
                return null;
            }
            if (object instanceof CalendarEntity) {
                CalendarEntity o = (CalendarEntity) object;
                return getStringKey(o.getId());
            } else {
                throw new IllegalArgumentException("object " + object + " is of type " + object.getClass().getName() + "; expected type: " + CalendarEntityController.class.getName());
            }
        }
    }
}
